package cn.zch.soft.util.process.host;
import lombok.extern.slf4j.Slf4j;
import sun.jvmstat.monitor.MonitoredHost;
import sun.jvmstat.monitor.MonitoredVm;
import sun.jvmstat.monitor.MonitoredVmUtil;
import sun.jvmstat.monitor.VmIdentifier;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
/**
 * @author zchcpywin10
 */
@Slf4j
public class ProcessInfoByClassName {
  public static void main(String[] args) {
    int pid = getProcess(ProcessInfoByClassName.class);
    log.info("PID: " + pid);
  }
  public static int getProcess(Class<?> cls) {
    try {
      if (cls == null) {
        return -1;
      }
      // 获取监控主机
      MonitoredHost local = MonitoredHost.getMonitoredHost("localhost");
      // 取得所有在活动的虚拟机集合
      Set<?> vmlist = Collections.unmodifiableSet(new HashSet<Object>(local.activeVms()));
      // 遍历集合，输出PID和进程名
      for (Object process : vmlist) {
        MonitoredVm vm = local.getMonitoredVm(new VmIdentifier("//" + process));
        // 获取类名
        String processName = MonitoredVmUtil.mainClass(vm, true);
        log.info("PID:{},NAME:{}", process, processName);
        if (cls.getName().equals(processName)) {
          log.info("TARGET PID:{},TARGET NAME:{}", process, processName);
          return Integer.parseInt(String.valueOf(process));
        }
      }
    }
    catch (Exception e) {
      log.error(e.getMessage());
    }
    return -1;
  }
}
